package com.yc.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yc.edu.pojo.*;
import com.yc.edu.service.*;
import com.yc.edu.utils.PageUtils;
import com.yc.edu.utils.UUIDUtil;
import com.yc.edu.vo.Post;
import com.yc.edu.vo.PostInfoVO;
import com.yc.edu.vo.PostWriteComment;
import com.yc.edu.vo.PostWriteForm;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author YC
 * @version 1.0
 */
@Service
public class PostServiceImpl implements PostService {
    @Resource
    UserService userService;

    @Resource
    PostInfoService postInfoService;

    @Resource
    PostStaticService postStaticService;

    @Resource
    PostCommentsService postCommentsService;

    // 对某个贴子进行回复
    @Override
    public Result comment(PostWriteComment postWriteComment, Integer recommend) {
        String postId = postWriteComment.getPostId();

        // 通过id 获取到 user信息
        User user = userService.getOne(
                new QueryWrapper<User>().eq("username", postWriteComment.getUsername()));
        QueryWrapper<PostStatic> wrapper =
                new QueryWrapper<PostStatic>().eq("post_id", postId);

        PostStatic postStatic = postStaticService.getOne(wrapper);
        // 增加一个回复
        postStatic.setComments(postStatic.getComments() + 1);

        PostComments postComments = new PostComments();
        postComments.setPostId(postId);
        postComments.setUsername(user.getUsername());
        postComments.setUserAvatar(user.getAvatar());
        postComments.setContent(postWriteComment.getContent());
        if (recommend==1){
            postComments.setRecommentFlag("推荐");
        }else {
            postComments.setRecommentFlag("不推荐");
        }
        System.out.println(recommend+"    dadadadadadadad");
        postComments.setZan(0);
        postComments.setCommentTime(LocalDateTime.now());

        postStaticService.updateById(postStatic);
        postCommentsService.save(postComments);
        return Result.success(postComments);
    }

    // 写一篇帖子
    @Override
    public Result write(PostWriteForm postWriteForm) {
        // 通过id 获取到 user信息
        User user = userService.getOne(
                new QueryWrapper<User>().eq("username", postWriteForm.getUsername()));
        PostInfoVO postInfo = new PostInfoVO();
        PostStatic postStatic = new PostStatic();

        // 随机生成一个postId
        String postId = UUIDUtil.uuid();
        postInfo.setPostId(postId);
        postInfo.setTitle(postWriteForm.getTitle());
        postInfo.setContent(postWriteForm.getContent());
        postInfo.setQuesLabelList(Arrays.asList(postWriteForm.getQuesLabel().split(",")));
        postInfo.setUsername(user.getUsername());
        postInfo.setUserAvatar(user.getAvatar());
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);
        postInfo.setCreateTime(formattedNow.toString());

        postStatic.setPostId(postId);
        postStatic.setCollect(0);
        postStatic.setZan(0);
        postStatic.setViews(0);
        postStatic.setComments(0);

        postStaticService.save(postStatic);
        postInfoService.save(postInfo);

        return Result.success(new Post(postId,postInfo,postStatic,null));
    }

    // 得到帖子(分页数据)  按回复数降序
    // 默认帖子内容只显示前70个字符
    // 默认回复内容只获取前三条/点赞数排序
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<PostStatic> pageStaitcInfo = postStaticService.page(
                new Query<PostStatic>().getPage(params),
                new QueryWrapper<PostStatic>()
                        .orderByDesc("comments")
        );

        List<Post> posts = pageStaitcInfo.getRecords().stream().map((staticInfo) -> {
            String postId = staticInfo.getPostId();
            PostInfo info =
                    postInfoService.getOne(
                            new QueryWrapper<PostInfo>().eq("post_id", postId));
            // 设置内容长度为 30
//            if (info.getContent().length() > 30) {
//                info.setContent(info.getContent().substring(0, 30));
//            }
//            List<PostComments> postAnswers =
//                    postCommentsService.list(
//                            new QueryWrapper<PostComments>().
//                                    eq("post_id", postId).
//                                    orderByDesc("zan").last("limit 5"));
            List<PostComments> postAnswers =
                    postCommentsService.list(
                            new QueryWrapper<PostComments>()
                                    .eq("post_id", postId)
                                    .orderByDesc("LENGTH(content)")
                                    .last("LIMIT 20"));

            // 转化为list
            PostInfoVO postInfoVO = new PostInfoVO();
            BeanUtils.copyProperties(info, postInfoVO);
            postInfoVO.setQuesLabelList(Arrays.asList(info.getQuesLabel().split(",")));

            Post post = new Post();
            post.setPostId(postId);
            post.setPostInfo(postInfoVO);
            post.setPostStatic(staticInfo);
            post.setPostCommentsList(postAnswers);
            return post;
        }).collect(Collectors.toList());

        return new PageUtils(posts, (int) pageStaitcInfo.getTotal(),
                (int) pageStaitcInfo.getSize(), (int) pageStaitcInfo.getCurrent());
    }

    @Override
    public PageUtils queryInfo(Map<String, Object> params) {
        QueryWrapper<PostInfo> wrapper = new QueryWrapper<>();
        String keyword = (String) params.get("keyword");

        if (StringUtils.hasText(keyword)) {
            wrapper.eq("user_name", keyword).or().
                    like("title", keyword).or().
                    in("ques_label", keyword);
        }

        IPage<PostInfo> pageInfoList = postInfoService.page(
                new Query<PostInfo>().getPage(params),
                wrapper
        );

        List<Post> posts = pageInfoList.getRecords().stream().map((info) -> {
            // 设置内容长度为 30
//            if (info.getContent().length() > 30) {
//                info.setContent(info.getContent().substring(0, 30));
//            }
            String postId = info.getPostId();
            PostStatic pStatic =
                    postStaticService.getOne(
                            new QueryWrapper<PostStatic>().eq("post_id", postId));
//            List<PostComments> postAnswers =
//                    postCommentsService.list(
//                            new QueryWrapper<PostComments>().
//                                    eq("post_id", postId).
//                                    orderByDesc("zan").
//                                    last("limit 5"));
            List<PostComments> postAnswers =
                    postCommentsService.list(
                            new QueryWrapper<PostComments>()
                                    .eq("post_id", postId)
                                    .orderByDesc("LENGTH(content)")
                                    .last("LIMIT 20"));

            // 转化为list
            PostInfoVO postInfoVO = new PostInfoVO();
            BeanUtils.copyProperties(info, postInfoVO);
            postInfoVO.setQuesLabelList(Arrays.asList(info.getQuesLabel().split(",")));

            Post post = new Post();
            post.setPostId(postId);
            post.setPostInfo(postInfoVO);
            post.setPostStatic(pStatic);
            post.setPostCommentsList(postAnswers);
            return post;
        }).collect(Collectors.toList());

        return new PageUtils(posts, (int) pageInfoList.getTotal(),
                (int) pageInfoList.getSize(), (int) pageInfoList.getCurrent());
    }

    @Override
    public List<PostComments> getAllComments(String postId) {
        return postCommentsService.list(
                new QueryWrapper<PostComments>().
                        eq("post_id", postId).
                        orderByDesc("zan"));
    }

    @Override
    public String getDetaiContent(String postId) {
        QueryWrapper<PostInfo> postInfo =
                new QueryWrapper<PostInfo>().eq("post_id", postId);
        QueryWrapper<PostStatic> postStatic =
                new QueryWrapper<PostStatic>().eq("post_id", postId);
        PostStatic staticBean = postStaticService.getOne(postStatic);
        PostInfo infoBean = postInfoService.getOne(postInfo);
        // 浏览量加 1
        staticBean.setViews(staticBean.getViews() + 1);

        postStaticService.updateById(staticBean);
        return infoBean.getContent();
    }

    @Override
    public void collectForPost(String postId, Integer count) {
        QueryWrapper<PostStatic> postWrapper =
                new QueryWrapper<PostStatic>().eq("post_id", postId);
        PostStatic one = postStaticService.getOne(postWrapper);
        one.setCollect(one.getCollect() + count);
        postStaticService.updateById(one);
    }

    @Override
    public void zanForPost(String postId, Integer count) {
        QueryWrapper<PostStatic> postWrapper =
                new QueryWrapper<PostStatic>().eq("post_id", postId);
        PostStatic one = postStaticService.getOne(postWrapper);
        one.setZan(one.getZan() + count);
        postStaticService.updateById(one);
    }

    @Override
    public void zanForComment(String commentId, Integer count) {
        QueryWrapper<PostComments> wrapper =
                new QueryWrapper<PostComments>().eq("id", commentId);
        PostComments one = postCommentsService.getOne(wrapper);
        one.setZan(one.getZan() + count);
        postCommentsService.updateById(one);
    }

}
